<template>
  <div @click="showDrawer" class="button">
    <slot> 按钮 </slot>
  </div>
  <a-drawer :width="968" v-model:open="open" placement="right" destroy-on-close>
    <template #title> {{ title }} </template>
    <a-form layout="vertical" :model="formState" ref="formRef">
      <a-form-item
        name="path"
        :label="title + '目录'"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-cascader
          change-on-select
          :loading="loading"
          v-model:value="formState.path"
          :load-data="loadData"
          :options="options"
          placeholder="请选择"
          @change="onChange"
        />
      </a-form-item>
    </a-form>
    <div style="margin-bottom: 30px">
      <a-checkbox v-model:checked="defaultSettingChecked">
        设为默认路径
      </a-checkbox>
    </div>
    <div style="margin-bottom: 30px">
      <presets-radio v-model:value="presetsValue" />
    </div>
    <a-space>
      <a-button type="primary" @click="onConfirm" :loading="submitLoading">
        确定
      </a-button>
      <a-button @click="onClose">取消</a-button>
    </a-space>
  </a-drawer>
</template>
<script setup>
import { onMounted, ref, reactive, toRaw, watch } from 'vue'
import PresetsRadio from './file-conflict-presets-radio.vue'
import { getCategoryTree, queryChildFolder } from '@/api/db.js'
import { useStorage } from '@vueuse/core'
import { useDbType } from './provide-context.js'
/**
 * 外部参数
 */
let props = defineProps({
  title: { type: String, required: true },
  confirm: { type: Function, required: true },
  cacheKey: { type: String, required: true },
  // data: { type: Object, required: true },
})
/**
 * 抽屉相关
 */
let open = ref(false)
let showDrawer = () => {
  open.value = true
}
/**
 * 表单
 */
let formRef = ref()
let formState = reactive({
  path: [],
})
/**
 * 数据
 */
let options = ref([])
let loading = ref(false)
let dbType = useDbType()
onMounted(async () => {
  loading.value = true
  try {
    let result = await getCategoryTree({}, dbType)
    options.value = result.data || []
    standardizationData(options.value)
  } catch (e) {}
  loading.value = false
})
function standardizationData(nodes) {
  nodes.forEach(node => {
    node.value = node.categoryId
    node.label = node.categoryName
    if (node.children instanceof Array && node.children.length > 0) {
      standardizationData(node.children)
    } else {
      node.isLeaf = false
    }
  })
}

// function getActiveInfo(nodes,id){
//   // let id = [...path].pop()

//   nodes.find(node => {
//     if(node.value === id){

//     }

//     if (node.children instanceof Array && node.children.length > 0) {
//       standardizationData(node.children)
//     } else {
//       node.isLeaf = false
//     }
//   })

// }
/**
 * 事件
 */
let submitLoading = ref(false)
async function onConfirm() {
  submitLoading.value = true
  try {
    await formRef.value.validate()
    await props.confirm(formState, presetsValue.value)
    open.value = false
  } catch (e) {
    console.log(e)
  }
  submitLoading.value = false
}
function onClose() {
  open.value = false
}
function onChange(path, pathInfo) {
  let info = [...pathInfo].pop()
  if (!(info.isLeaf === false || !info.children)) {
    formState.path = []
  }
}
/**
 * 默认路径
 */
let defaultSettingChecked = useStorage(
  import.meta.env.VITE_APP_ID + props.cacheKey + '-(defaultSettingChecked)',
  false,
)
let defaultSettingValue = useStorage(
  import.meta.env.VITE_APP_ID + props.cacheKey + '-(defaultSettingValue)',
  [],
)
if (defaultSettingChecked.value) {
  formState.path = [...defaultSettingValue.value]
}
watch(
  () => formState.path,
  path => {
    defaultSettingValue.value = [...path]
  },
)

/**
 * 预设值
 */
let presetsValue = ref(1)
/**
 * 加载文件夹目录
 */
async function loadData(selectedOptions) {
  let targetOption = selectedOptions[selectedOptions.length - 1]
  targetOption.loading = true
  if (targetOption && targetOption.isLeaf === false) {
    let result = await queryChildFolder(
      { parentId: targetOption.value },
      dbType,
    )
    targetOption.loading = false
    targetOption.children = (result.data || []).map(({ fileName, id }) => ({
      label: fileName,
      value: id,
    }))
    options.value = [...options.value]
  }
}
</script>
<style scoped lang="less"></style>
